<?php

namespace App\Service\Push;

use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Jobs\Message\FsMessageJob;
use App\Library\Rms\RmsUserApi;
use App\Models\Common\ConfigModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Common\FsCompanyUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Service\BaseService;
use App\Support\OrganizationManageFsRobotSendSupport;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 推送，组装业务飞书推送结构
 */
class PushComposeService extends BaseService
{
    /**
     * PushBaseFuncService
     */
    protected PushAbstractFuncService $pushBaseFuncService;
    private bool $prodDebug;

    public function __construct(PushAbstractFuncService $pushBaseFuncService)
    {
        $this->pushBaseFuncService = $pushBaseFuncService;
        $this->prodDebug = (bool)config('open-shop.task-push-debug');
    }

    private array $taskLists = [];

    private function pushTaskLists(int $task)
    {
        $funcName = "task{$task}";

        if (!method_exists($this->pushBaseFuncService, $funcName)) {
            return;
        }

        $this->pushBaseFuncService->setTask($task);
        $this->taskLists = array_merge($this->taskLists, $this->pushBaseFuncService->{$funcName}());
    }

    // 汇总 - 根据推送类型，获取每条任务明细
    private function aggTasks(int $bizType): Collection
    {
        $this->taskLists = [];

        $appTypes = PushConfigService::frame()[$bizType];
        foreach ($appTypes as $tasks) {
            foreach ($tasks as $task) {
                if (is_array($task)) {
                    foreach ($task as $t) {
                        $this->pushTaskLists($t);
                    }
                } else {
                    $this->pushTaskLists($task);
                }

                // 任务数量可控，降低cpu负载，避免报警
                if (isProd()) {
                    sleep(1);
                }
            }
        }

        $tmpLists = [];
        foreach ($this->taskLists as $val) {
            $tmpLists["{$val['task']}:{$val['userId']}:{$val['uuid']}"] = $val;
        }
        $this->taskLists = array_values($tmpLists);

        // 查询用户一级部门
        $fsLists = collect((new RmsUserApi())->getFsUsers('',
                ['rmsUserId', 'rootDepartmentName', 'departmentName'])['data']['lists'] ?? [])
            ->where('rootDepartmentName', '!=', '')
            ->map(function ($item) {
                $suffix = (mb_substr($item['rootDepartmentName'], -3));
                if ($suffix == '分公司') {
                    $item['provinceAreaPrefix'] = mb_substr($item['rootDepartmentName'], 0, 3);
                    $item['provinceAreaPrefix'] = rtrim($item['provinceAreaPrefix'], '分');

                    if ($item['provinceAreaPrefix'] == '江苏') {
                        $item['provinceAreaPrefix'] = mb_substr($item['departmentName'], 0, 3);
                    }

                } else {
                    $item['provinceAreaPrefix'] = '';
                }

                return $item;
            })
            ->filter()
            ->values()
            ->keyBy('rmsUserId');

        // 用户名
        $userIds   = array_values(array_unique(array_column($this->taskLists, 'userId')));
        $userInfos = collect((new RmsUserApi())->getUserInfoByIds($userIds,
                ['id', 'username'])['data'] ?? [])->keyBy('id');

        return collect($this->taskLists)->map(function ($item) use ($fsLists, $userInfos) {
            $item['manage']     = $fsLists[$item['userId']]['provinceAreaPrefix'] ?? '';
            $item['department'] = $fsLists[$item['userId']]['rootDepartmentName'] ?? '';
            $item['userName']   = $userInfos[$item['userId']]['username'] ?? '';

            Cache::store('array')
                 ->set('pushUserName:' . $item['userId'], $item['userName']);

            // dev debug
//            if (config('app.env') == 'dev') {
//                if (in_array($item['userId'], [1, 6]) && $item['manage'] == '') {
//                    $item['manage']     = '上海';
//                    $item['manageId']   = 10;
//                    $item['department'] = '创业商学院';
//                }
//            }

            return $item;
        });
    }

    /**
     * 按用户
     * @return array
     */
    public function composeUser(): array
    {
        $result = [];

        // 获取涉及到的所有任务明细
        $lists = $this->aggTasks(PushConfigService::BIZ_TYPE_USER);

        // 用户白名单
        $whiteUserIds = [];
        if ($this->prodDebug == true) {
            $whiteUserIds = (array)ConfigModel::getValue('openShop', 'taskPushUserWhiteList');

            if ($whiteUserIds) {
                dump('white user list hit...', $whiteUserIds);
                $lists = $lists->whereIn('userId', $whiteUserIds);
            }
        }

        $lists->pluck('userId')
              ->each(function ($userId) use ($lists, &$result) {

                  // 当前用户的所有任务
                  $userTaskLists = $lists->where('userId', $userId);

                  // 按app分类
                  $appTypes = PushConfigService::frame()[PushConfigService::BIZ_TYPE_USER];
                  foreach ($appTypes as $appType => $tasks) {

                      // 当前app分类下的所有任务明细
                      $appTaskLists = $userTaskLists->whereIn('task', $tasks)
                                                    ->values();

                      $result[$userId][$appType] = [

                          // 当前app分类 - 合计任务数量
                          'totalNum'   => $appTaskLists->count(),

                          // 当前app分类 - 每个单独任务的聚合明细
                          'taskGroups' => $appTaskLists
                              ->groupBy('task')
                              ->map(function ($groupTask) {

                                  // 取最老的任务
                                  $firstTask = $groupTask
                                      ->sortBy('createdAt')
                                      ->first();

                                  $firstTask['taskNum'] = $groupTask->count();

                                  $taskName = PushConfigService::ENUM_TEXT[$firstTask['task'] ?? ''] ?? '';

                                  return "\n（{$taskName}：{$firstTask['taskNum']}个）";
                              })
                              ->implode(''),

                          // 查看详情
                          'module'     => PushConfigService::APP_MODULE[$appType] ?? '',
                      ];
                  }
              });

        Log::debug("composeUser", $result);

        $userModules = $this->getUserModule($lists->pluck('userId')->unique()
                                                  ->toArray());
        Log::debug('userModules', $userModules);

        // 发送飞书消息
        foreach ($result as $userId => $appTypes) {

            $totalNum = 0;

            $path         = 'OpenShop/feishu/notifyTemplate/taskToUser.json';
            $templateJson = vsprintf(file_get_contents(resource_path($path)), []);
            $templateArr  = json_decode($templateJson, true);

            foreach ($appTypes as $appType => $val) {

                $totalNum += ($val['totalNum'] ?? 0);

                $paramsTotalNum    = ($val['totalNum'] ?? 0);
                $paramsTaskGroups  = $val['taskGroups'] ?? '';
                $paramsAppTypeText = PushConfigService::ENUM_TEXT[$appType] ?? '';

                if ($paramsTotalNum == 0) {
                    continue;
                }

                // 对应链接j
                $module  = $val['module'];
                $miniUrl = $this->miniUrl($module, '');
                $pcUrl   = $this->pcUrl($appType);

                if (in_array($appType, [PushConfigService::APP_TYPE_OPEN])) {
                    $extra = [
                        'tag'       => 'button',
                        'text'      => [
                            'tag'     => 'lark_md',
                            'content' => '查看详情',
                        ],
                        'type'      => 'primary',
                        'multi_url' => [
                            'url'         => $pcUrl,
                            'android_url' => $miniUrl,
                            'ios_url'     => $miniUrl,
                            'pc_url'      => $pcUrl,
                        ],
                    ];

                } elseif (in_array($appType, [
                    PushConfigService::APP_TYPE_WORK_ORDER,
                    PushConfigService::APP_TYPE_COLLEGE
                ])) {
                    $extra = [
                        'tag'  => 'button',
                        'text' => [
                            'tag'     => 'lark_md',
                            'content' => '查看详情',
                        ],
                        'type' => 'primary',
                        'url'  => $pcUrl,
                    ];
                } else {

                    $extra = [
                        'tag'  => 'button',
                        'text' => [
                            'tag'     => 'lark_md',
                            'content' => '查看详情',
                        ],
                        'type' => 'primary',
                        'url'  => $miniUrl,
                    ];
                }

                $templateArr['elements'][] = [
                    'tag'   => 'div',
                    'text'  => [
                        'tag'     => 'lark_md',
                        'content' => "您还有{$paramsTotalNum}个{$paramsAppTypeText}任务待处理{$paramsTaskGroups}",
                    ],
                    "extra" => $extra,
                ];

                $templateArr['elements'][] = [
                    'tag' => 'hr',
                ];
            }

            $username = Cache::store('array')
                             ->get('pushUserName:' . $userId, '');

            $templateArr['header']['title'] = [
                'content' => "⏰ 亲爱的{$username}，您有 {$totalNum}个任务待处理",
                'tag'     => 'plain_text',
            ];

            $templateArr['elements'][] = json_decode('{
      "elements": [
        {
          "alt": {
            "content": "",
            "tag": "plain_text"
          },
          "img_key": "img_v2_5edf81bb-d197-4ea1-a9ab-752c8105997g",
          "tag": "img"
        },
        {
          "content": "快速完成处理，提升工作效率",
          "tag": "plain_text"
        }
      ],
      "tag": "note"
    }', true);

            $sendModule = $userModules[$userId]['module'];
            $feishuId   = $userModules[$userId]['feishuId'];

            if ($whiteUserIds) {
                OrganizationManageFsRobotSendSupport::send(13, '', '', 'feishuRobotDataDay', $templateArr);

            } else {

                // 正常给用户推送
                $this->sendToUser($feishuId, $templateArr, $sendModule);
            }
        }

        return $result;
    }

    /**
     * 总部
     * @return array
     */
    public function composeKf(): array
    {
        // 获取涉及到的所有任务明细
        $lists = $this->aggTasks(PushConfigService::BIZ_TYPE_KF);

        $details = [

            // 省区待处理明细
            PushConfigService::REGION_TYPE_PROVINCE => collect($this->composeProvince(false))
                ->map(function ($item) {
                    unset($item['users']);
                    $item['titleText'] = $item['manage'] . '分公司';
                    return $item;
                })
                ->sortByDesc('totalNum'),

            // 总部待处理明细
            PushConfigService::REGION_TYPE_KF       => $this->dealAppTypesByRegionType($lists,
                PushConfigService::REGION_TYPE_KF),

            // 三方待处理明细
            PushConfigService::REGION_TYPE_EXT      => $this->dealAppTypesByRegionType($lists,
                PushConfigService::REGION_TYPE_EXT),
        ];

        // 飞书推送
        $totalNum     = 0;
        $totalTextArr = [];
        foreach ($details as $regionType => $taskLists) {
            foreach ($taskLists as $company) {
                $totalNum += $company['totalNum'];

                foreach ($company['appTypes'] as $appType => $t) {

                    if ($t['totalNum'] == 0) {
                        continue;
                    }

                    if (isset($totalTextArr[$appType]['totalNum'])) {
                        $totalTextArr[$appType]['totalNum'] += $t['totalNum'];
                    } else {
                        $totalTextArr[$appType]['totalNum'] = $t['totalNum'];
                    }
                }
            }
        }

        $params = [
            date('Y-m-d'),
            $totalNum,
            $this->totalText($totalTextArr),
        ];

        $path         = 'OpenShop/feishu/notifyTemplate/taskToKf.json';
        $templateJson = vsprintf(file_get_contents(resource_path($path)), $params);
        $templateArr  = json_decode($templateJson, true);

        foreach ($details as $regionType => $taskLists) {

            $regionText = PushConfigService::ENUM_TEXT[$regionType] ?? '';

            $templateArr['elements'][] = [
                'tag'     => 'markdown',
                'content' => "**#{$regionText}待处理任务明细**",
            ];

            $sId = 1;
            foreach ($taskLists as $company) {
                $titleText = $company['titleText'] ?? '';
                if ($company['totalNum'] == 0) {
                    continue;
                }

                $content = "**{$sId}**、{$titleText} ： **{$company['totalNum']}**个\n";
                foreach ($company['appTypes'] as $appType => $appTypeTask) {
                    $content .= $this->detailContent($appTypeTask, $appType);
                }

                $templateArr['elements'][] = [
                    'tag'  => 'div',
                    'text' => [
                        'tag'     => 'lark_md',
                        'content' => $content,
                    ]
                ];

                $templateArr['elements'][] = ['tag' => 'hr'];


                $sId++;
            }
        }
        $templateArr[] = [
            'tag'     => 'markdown',
            'content' => '**#省区待处理任务明细**',
        ];

        $templateArr['elements'][] = json_decode('{
      "elements": [
        {
          "alt": {
            "content": "",
            "tag": "plain_text"
          },
          "img_key": "img_v2_5edf81bb-d197-4ea1-a9ab-752c8105997g",
          "tag": "img"
        },
        {
          "content": "快速完成处理，提升工作效率",
          "tag": "plain_text"
        }
      ],
      "tag": "note"
    }', true);

        if (!$templateArr) {
            Log::warning("templateJson empty: {$templateJson}");
            return [];
        }

        // 推台湾测试分公司群
        if ($this->prodDebug == true) {
            $manageId = 13;
        } else {
            $manageId = 100;
        }

        OrganizationManageFsRobotSendSupport::send($manageId, '', '', 'feishuRobotDataDay', $templateArr);

        return $details;
    }

    // 按省区
    public function composeProvince(bool $send = true): array
    {
        // 获取涉及到的所有任务明细
        $lists = $this->aggTasks(PushConfigService::BIZ_TYPE_PROVINCE);

        $whiteManageIds = [];
        if ($this->prodDebug == true) {
            $whiteManageIds = (array)ConfigModel::getValue('openShop', 'taskPushProvinceWhiteList');

            if ($whiteManageIds) {
                dump('white province list hit...', $whiteManageIds);
            }
        }

        // 准备各省区的数据
        $result = OpenShopOrganizationManageModel
            ::query()
            ->where('type', OpenShopOrganizationManageModel::TYPE_PROVINCE)
            ->when($whiteManageIds, function ($query) use ($whiteManageIds) {
                $query->whereIn('id', $whiteManageIds);
            })
            ->select('name', 'id')
            ->get()
            ->map(function ($item) {
                return [
                    'id'   => $item->id,
                    'name' => mb_substr($item->name, 0, -3, 'utf-8'),
                ];
            })
            ->map(function ($item) use ($lists) {

                // 省区下的所有任务
                $provinceTasks = $lists->where('manage', $item['name']);

                // 每个用户的明细
                $users = $provinceTasks
                    ->groupBy('userId')
                    ->map(function ($userTaskLists, $userId) {
                        return [
                            'userId'   => $userId,
                            'userName' => $userTaskLists->first()['userName'] ?? '',
                            'taskNum'  => $userTaskLists->count(),
                            'appTypes' => collect(PushConfigService::frame()[PushConfigService::BIZ_TYPE_PROVINCE])
                                ->map(function ($tasks, $appType) use ($userTaskLists, $userId) {
                                    return $this->dealAppTypeTasks($tasks, $appType, $userTaskLists);
                                }),
                        ];
                    })
                    ->sortByDesc('taskNum')
                    ->values();

                // 当天任务概要
                $totalTasks = collect(PushConfigService::frame()[PushConfigService::BIZ_TYPE_PROVINCE])
                    ->map(function ($tasks, $appType) use ($provinceTasks) {
                        return $this->dealAppTypeTasks($tasks, $appType, $provinceTasks);
                    })
                    ->keyBy('task')
                    ->toArray();

                $totalNum = (int)collect($totalTasks)->sum('totalNum');

                return [
                    'manage'   => $item['name'],
                    'manageId' => $item['id'],
                    'users'    => $users,
                    'totalNum' => $totalNum,
                    'appTypes' => $totalTasks,
                ];
            })
            ->toArray();

        if (!$send) {
            return $result;
        }

        // 发送飞书消息
        foreach ($result as $manageVal) {
            $manage = $manageVal['manage'];

            // 当天任务概要
            $totalNum   = $manageVal['totalNum'];
            $totalTasks = $manageVal['appTypes'];

            $params = [
                date('Y-m-d'),
                $totalNum,
                $this->totalText($totalTasks),
                $manage,
            ];

            $path         = 'OpenShop/feishu/notifyTemplate/taskToProvince.json';
            $templateJson = vsprintf(file_get_contents(resource_path($path)), $params);
            $templateArr  = json_decode($templateJson, true);

            // 待处理任务明细
            foreach ($manageVal['users'] as $k => $user) {
                $sId = $k + 1;

                $content = "**{$sId}**、{$user['userName']}** {$user['taskNum']}**个\n";
                foreach ($user['appTypes'] as $appType => $appTypeTask) {
                    $content .= $this->detailContent($appTypeTask, $appType);
                }

                $templateArr['elements'][] = [
                    'tag'  => 'div',
                    'text' => [
                        'tag'     => 'lark_md',
                        'content' => $content,
                    ]
                ];
            }

            $templateArr['elements'][] = ['tag' => 'hr'];
            $templateArr['elements'][] = json_decode('{
      "elements": [
        {
          "alt": {
            "content": "",
            "tag": "plain_text"
          },
          "img_key": "img_v2_5edf81bb-d197-4ea1-a9ab-752c8105997g",
          "tag": "img"
        },
        {
          "content": "快速完成处理，提升工作效率",
          "tag": "plain_text"
        }
      ],
      "tag": "note"
    }', true);

            if (!$templateArr) {
                Log::warning("templateJson empty: {$templateJson}");
                continue;
            }

            // 推台湾测试分公司群
            if ($this->prodDebug == true) {
                $manageId = 13;
            } else {
                $manageId = $manageVal['manageId'];
            }

            dispatch(function () use ($manageId, $templateArr) {
                OrganizationManageFsRobotSendSupport::send($manageId, '', '', 'feishuRobotDataDay', $templateArr);
                sleep(1); // 防止太频繁被飞书限流
            });
        }

        return $result;
    }

    /**
     * 发送飞书推送
     * @param string $feishuId
     * @param string $templateJson
     * @param string $module
     * @return void
     */
    private function sendToUser(string $feishuId, array $templateArr, string $module): void
    {
        if (!$feishuId || !$module) {
            Log::warning("send fs empty: {$feishuId} {$module}");
            return;
        }

        if (!$templateArr) {
            Log::warning("templateJson decode error");
            return;
        }

        $microseconds = 1000000; // 1秒 防止太频繁被飞书限流
        dispatch((new FsMessageJob($feishuId, $templateArr, $module, $microseconds)));
    }

    /**
     * 小程序推送地址
     * @param string $module
     * @param string $path
     * @return string
     */
    private function miniUrl(string $module, string $path = ''): string
    {
        if (!$path) {
            switch ($module) {
                case UserPermissionAuth::MODULE_OPEN_SHOP:
                    $path = '/pages/task-list/index';
                    break;
                case UserPermissionAuth::MODULE_OPEN_SITE:
                    $path = '/pages/index/index';
                    break;
                case UserPermissionAuth::MODULE_CRUISE:
                    $path = '/pages/index/index';
                    break;
                case UserPermissionAuth::MODULE_CRUISE_CHECK:
                    $path = '/pages/task-list/index';
                    break;
                default:
                    $path = '/pages/task-list/index';
            }
        }

        $appid = ConfigModel::getFsConfigByPlatformNameOrgId($module, 0)['appId'] ?? '';
        $path = urlencode($path);

        return "https://applink.feishu.cn/client/mini_program/open?appId={$appid}&mode=window-semi&relaunch=true&path={$path}";
    }

    /**
     * pc推送地址
     * @return string
     */
    private function pcUrl(string $appType): string
    {
        $appid = ConfigModel::getFsConfigByPlatformNameOrgId('openShop', 0)['appId'] ?? '';

        switch ($appType) {
            case PushConfigService::APP_TYPE_OPEN:
                $path  = "openShop/index/list";
                break;
            case PushConfigService::APP_TYPE_WORK_ORDER:
                $path  = "workOrder/manage/list";
                break;
            case PushConfigService::APP_TYPE_COLLEGE:
                $path  = "college/training_plan/index";
                break;
            default:
                $path  = "openShop/index/list";
        }

        return "https://applink.feishu.cn/client/web_app/open?appId={$appid}&path=$path";
    }

    /**
     * 获取用户推送的module&feishuId
     * @param array $userIds
     * @return array
     */
    private function getUserModule(array $userIds): array
    {
        // 本部人的feishuIds
        $kfUsers = collect((new RmsUserApi())->getUserInfoByIds($userIds, ['id', 'feishuUserId'])['data'])->keyBy('id');

        // 过滤出三方人员
        $supplierUserIds = FsCompanyUserModel::filterKfUsers($userIds);

        return collect($userIds)
            ->map(function ($userId) use ($supplierUserIds, $kfUsers) {

                // 三方稽核
                if (isset($supplierUserIds[$userId])) {
                    return [
                        'userId'   => $userId,
                        'module'   => 'cruiseCheckSupplier',
                        'feishuId' => $supplierUserIds[$userId]['feishuId'],
                    ];
                }

                // 夸父总部
                return [
                    'userId'   => $userId,
                    'module'   => UserPermissionAuth::MODULE_OPEN_SHOP,
                    'feishuId' => $kfUsers[$userId]['feishuUserId'] ?? '',
                ];
            })
            ->keyBy('userId')
            ->toArray();
    }


    private function dealAppTypesByRegionType(Collection $lists, int $regionType): Collection
    {
        $kfResult = collect();

        $appTypes = PushConfigService::frame()[PushConfigService::BIZ_TYPE_KF][$regionType];
        foreach ($appTypes as $department => $tasks) {

            // 根据task+uuid去重
            $dTasks = $lists->whereIn('task', $tasks)->keyBy(function ($item) {
                return $item['task'] . '-' . $item['uuid'];
            })->values();

            // 仅查询当前部门人员的任务
            if ($regionType == PushConfigService::REGION_TYPE_KF) {
                $departmentText = PushConfigService::ENUM_TEXT[$department] ?? '';
                $dTasks         = $dTasks->where('department', $departmentText);
            }

            if ($dTasks->count()) {
                $kfResult[$department] = [
                    'department' => $department,
                    'titleText'  => PushConfigService::ENUM_TEXT[$department] ?? '',
                    'totalNum'   => $dTasks->count(),
                    'appTypes'   => collect(PushConfigService::APP_TYPE_TO_TASKS)
                        ->map(function ($tasks, $appType) use ($dTasks) {
                            $t = $this->dealAppTypeTasks($tasks, $appType, $dTasks);
                            if ($t['totalNum'] == 0) {
                                return null;
                            }

                            return $t;
                        })
                        ->filter(),

                ];
            }
        }

        return collect($kfResult)->sortByDesc('totalNum');
    }

    /**
     * 处理一个模块下的任务统计
     * @param array $moduleTasks
     * @param int $appType
     * @param Collection $fullTaskLists
     * @return array
     */
    private function dealAppTypeTasks(array $moduleTasks, int $appType, Collection $fullTaskLists): array
    {
        // 当前app分类下的所有任务明细
        $appTaskLists = $fullTaskLists->whereIn('task', $moduleTasks)
                                      ->values();

        // 商家部分的任务
        $merchantTaskLists = $appTaskLists->whereIn('task', PushConfigService::MERCHANT_TASKS)
                                          ->values();

        return [

            // 当前app分类 - 合计任务数量
            'totalNum'      => $appTaskLists->count(),
            'module'        => PushConfigService::APP_MODULE[$appType] ?? '',
            'task'          => $appType,

            // 模块下的最长滞留时间
            'longest'       => $appTaskLists->sortBy('createdAt')
                                            ->first()['createdAt'] ?? 0,
            // 需要商家确认的任务
            'merchantTasks' => $merchantTaskLists->groupBy('task')
                                                 ->map(function ($ts) {
                                                     return [
                                                         'task'     => $ts->first()['task'],
                                                         'taskName' => $ts->first()['taskName'],
                                                         'num'      => $ts->count(),
                                                     ];
                                                 })
        ];
    }

    /**
     * @param $totalTasks
     * @return string
     */
    private function totalText($totalTasks): string
    {
        if (is_array($totalTasks)) {
            $totalTasks = collect($totalTasks);
        }
        $totalTasks = $totalTasks->sortByDesc('totalNum');

        $totalText = '';

        foreach ($totalTasks as $appType => $val) {
            $num       = $val['totalNum'];
            $totalText .= "\\n" . PushConfigService::ENUM_TEXT[$appType] . '任务数：' . $num . '个';

            foreach ($val['merchantTasks'] ?? [] as $task) {
                $totalText .= "（{$task['taskName']}：{$task['num']}个）";
            }
        }

        return $totalText;
    }

    private function detailContent(array $appTypeTask, int $appType): string
    {
        $content = '';

        if ($appTypeTask['totalNum'] == 0) {
            return $content;
        }

        $content .= PushConfigService::ENUM_TEXT[$appType] . "：" . $appTypeTask['totalNum'] . '个，';

        foreach ($appTypeTask['merchantTasks'] as $merchantTask) {
            $content .= "（{$merchantTask['taskName']}：{$merchantTask['num']}个）";
        }

        $jamDay  = ceil((time() - $appTypeTask['longest']) / 86400);
        $content .= "最长滞留：{$jamDay}天\n";

        return $content;
    }
}
